package com.autonavi.minimap.util.TaskEngine;

import java.util.ArrayList;

import android.util.Log;

import com.autonavi.minimap.threadpool.DDAIThreadPool;
import com.autonavi.minimap.threadpool.IDThreadPool;
import com.autonavi.minimap.threadpool.IPriorityTask;

public final class TaskManager {

	// store instances.
	public static ArrayList<TaskManager> instances = new ArrayList<TaskManager>();

	// Thread Pool to handle task.
	private IDThreadPool downloadThreadQueue;

	// Unique value
	public int flag = 0;

	private TaskManager(int flag, boolean timeSortASC) {
		Log.e("DDAI", "cpu=" + Runtime.getRuntime().availableProcessors());
		downloadThreadQueue = DDAIThreadPool.newFixedThreadPool(Runtime
				.getRuntime().availableProcessors(), !timeSortASC);
		this.flag = flag;
		
	}

	public static TaskManager getInstance(int flag, boolean timeSortASC) {
		TaskManager result = null;
		for (TaskManager instance : instances) {
			if (instance.flag == flag) {
				result = instance;
				break;
			}
		}
		if (result == null) {
			result = new TaskManager(flag, timeSortASC);
		}
		return result;
	}

	public int put(String category, IPriorityTask runnable, int retry,
			int prority) {
		final int taskID = runnable.hashCode();
		if (runnable instanceof BaseProrityTask) {
			((BaseProrityTask) runnable).set(downloadThreadQueue, retry,
					category);
		}
		downloadThreadQueue.put(category, runnable, prority);
		return taskID;
	}

	public void cancelTsak(int taskId) {
		downloadThreadQueue.cancelQueueByTaskID(taskId);
	}

}
